package inc.monsters.mias.conversion;

import inc.monsters.mias.data.FoodList;

import java.util.Collection;

import javax.faces.component.StateHolder;
import javax.faces.component.UIComponent;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.apache.myfaces.trinidad.bean.FacesBean;
import org.apache.myfaces.trinidad.bean.FacesBeanImpl;
import org.apache.myfaces.trinidad.bean.PropertyKey;
import org.apache.myfaces.trinidad.convert.ClientConverter;

public class FoodListConverter implements Converter, ClientConverter,
		StateHolder {
	private static final FacesBean.Type TYPE = new FacesBean.Type();
	private static final PropertyKey SEPARATOR = TYPE.registerKey("foodListConverterSeparator", String.class);
	private FacesBean facesBean = new FacesBeanImpl() {
		@Override
		public Type getType() {
			return TYPE;
		}
	};

	public Object getAsObject(FacesContext context, UIComponent component,
			String string) {
		String[] list = string.split(getSeparator());
		FoodList foodList = new FoodList();
		for (String food : list) {
			foodList.add(food);
		}
		return foodList;
	}

	public String getAsString(FacesContext context, UIComponent component,
			Object foodList) {
		if (foodList != null) {
			return ((FoodList) foodList).toStringWithSeparator(getSeparator());
		} else {
			return "";
		}
	}

	public String getSeparator() {
		return (String) facesBean.getProperty(SEPARATOR);
	}

	public void setSeparator(String separator) {
		facesBean.setProperty(SEPARATOR, separator);
	}

	public String getClientConversion(FacesContext context,
			UIComponent component) {
		return "new FoodListConverter('" + getSeparator() + "');";
	}

	public Collection<String> getClientImportNames() {
		return null;
	}

	public String getClientLibrarySource(FacesContext context) {
		ExternalContext ec = context.getExternalContext();
		return ec.getRequestContextPath() + "/scripts/FoodListConverter.js";
	}

	public String getClientScript(FacesContext context,
			UIComponent arg1component) {
		return null;
	}

	// The next four methods implement the StateHolder interface
	public boolean isTransient() {
		return false;
	}

	public void setTransient(boolean arg0) {
	}

	public void restoreState(FacesContext context, Object state) {
		facesBean.restoreState(context, state);
	}

	public Object saveState(FacesContext context) {
		return facesBean.saveState(context);
	}
}
